// pages/goods/goods.js
const { getGoodsDetail, getRelated, joinCart, getCartCount, collectGoods } = require('../../api/index.js')
const WxParse = require('../../lib/wxParse/wxParse.js');
const app = getApp()
Page({
  data: {
    inavHeight: 0,
    inavTop: 0,
    actionSheetStatus: false,
    obj: {},
    id: "",
    cartCount: 0,
    relatedList: []
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 获取规格组件
    this.actionSheet = this.selectComponent("#actionSheet")
  },
  showActionSheet() { //规格组件显示
    this.actionSheet.openActionSheet();
  },
  async getGoodsDetail() { //获取商品详情
    const res = await getGoodsDetail(this.data.id)
    this.setData({
      obj: res
    })
    var that = this;
    WxParse.wxParse('article', 'html', res.info.goods_desc, that, 0);
  },
  previewGallery(e) { //图片预览
    let arr = [];
    let gallery = this.data.obj.gallery
    if(gallery.length>0) {
      gallery.map(item => {
        arr.push(item.img_url)
      })
    }
    wx.previewImage({
      urls: arr,
      current: e.currentTarget.dataset.src
    })
  },
  toAll() { //跳转全部评论
    wx.navigateTo({
      url: '/pages/comments/comments?id=' + this.data.id,
    })
  },
  async getRelated() { //大家都在看
    const res = await getRelated(this.data.id)
    this.setData({
      relatedList: res
    })
    console.log(res)
  },
  async joinCart() { //加入购物车
    if (!this.data.actionSheetStatus) {
      this.setData({
        actionSheetStatus: true
      })
      return;
    }
    try {
      const res = await joinCart({
        goodsId: this.data.id,
        number: this.actionSheet.data.count,
        productId: this.data.obj.productList[0].id
      });
      this.setData({
        actionSheetStatus: false,
        cartCount: res.cartTotal.goodsCount
      })
    }catch(err) {}
  },
  async getCartCount() { //获取购物车商品数量
    const res = await getCartCount()
    this.setData({
      cartCount: res.cartTotal.goodsCount
    })
  },
  handelActionSheet(e) { //接收子组件发送的事件和数据
    console.log(e)
    this.setData({
      actionSheetStatus: e.detail.dialogStatus
    })
  },
  async collectGoods() { //商品收藏或取消收藏
    const res = await collectGoods({
      typeId: 0,
      valueId: this.data.id
    })
    if (res.type === 'add') {
      wx.showToast({
        title: '收藏成功'
      })
      this.setData({
        'obj.userHasCollect': 1
      })
    } else {
      wx.showToast({
        title: '取消收藏成功'
      })
      this.setData({
        'obj.userHasCollect': 0
      })
    }
  },
  onLoad: function (options) { //监听页面加载
    let id = options.id
    this.setData({
      inavHeight: app.globalData.inavHeight,
      inavTop: app.globalData.inavTop,
      id
    })
    this.getGoodsDetail()
    this.getCartCount()
    this.getRelated()
  },
  onShareAppMessage: function () { //用户点击右上角分享
  }
})